package com.solution.pc.my.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.product.entity.ProductBrandEntity;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductCategoryPropertyFilterEntity;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductPropertyEntity;
import com.solution.admin.product.service.ProductBrandService;
import com.solution.admin.product.service.ProductCategoryPropertyFilterService;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductService;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.product.entity.ProductSearchFilterEntity;

/**
 * 我的报价单
 * @author xkl
 * @date 2017年12月11日 下午2:54:06
 */
@RequestMapping("/pc/my")
@Controller("myQuotationController")
public class MyQuotationController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(MyQuotationController.class);

	@Autowired
	private ProductBrandService productBrandService;

	@Autowired
	private ProductCategoryService productCategoryService;

	@Autowired
	private ProductCategoryPropertyFilterService productCategoryPropertyFilterService;

	@Autowired
	private ProductService productService;

	/**
	 * 查询报价单
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月11日 下午2:13:41
	 */
	@RequestMapping("/quotation")
	public String quotation(HttpServletRequest request, Model model) {

		/** 1、所有的用户请求参数 */
		// 组装查询条件，用于页面显示已经选择的筛选项
		List<ProductSearchFilterEntity> filterNameList = new ArrayList<ProductSearchFilterEntity>();
		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		// 商品分类
		/*String categoryIdStr = request.getParameter("categoryId");*/
		// 商品分类（单个商品分类进来的话，还是把它当成第一种）
		String productCategoryId = request.getParameter("categoryId");
		// 搜索关键字（根据商品分类查询）
		String productSearchKey = request.getParameter("searchKey");
		// 解决以GET方式提交的中文乱码
		try {
			if (request.getMethod().toUpperCase().equals("GET") && null != productSearchKey) {
				productSearchKey = new String(productSearchKey.getBytes("ISO-8859-1"), "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		// 品牌
		String brandId = request.getParameter("brandId");
		String brandIds = request.getParameter("brandIds");
		// 筛选项查询条件
		String propertyFilter = request.getParameter("propertyFilter");
		// 价格(最低价-最高价)
		String minPrice = request.getParameter("minPrice");
		String maxPrice = request.getParameter("maxPrice");
		// 商品标签
		String productTag = request.getParameter("productTag");
		try {
			/** 2、初始化页面的数据（商品分类） */
			List<ProductCategoryEntity> topCategoryList = initProductCategoryData();
			model.addAttribute("topCategoryList", topCategoryList);
			/**
			 * 3、先拿到所有的查询参数，查询到对应商品列表<br>
			 * 查询类型一般分3种<br>
			 * 1、选中多个分类进行搜索<br>
			 * 2、输入关键字搜索（商品名称、商品关键字）带出所有商品的类型集合<br>
			 * 3、全部商品检索（无关键字、无类型）<br>
			 * TODO：可能会需要支持既有关键字又有类型的<br>
			 * */
			/* 第一种 */
			// 组装页面显示所需要的商品分类
			List<Long> categoryIdList = new ArrayList<Long>();
			param.put("status", 1);
			param.put("isDelete", 1);
			if (StringUtil.isNotNull(productCategoryId)) {
				// 有逗号分隔，说明是多个分类，不需要查询子分类
				if(productCategoryId.contains(",")) {
					String[] categoryIdArr = productCategoryId.split(",");
					for (String categoryId : categoryIdArr) {
						categoryIdList.add(Long.parseLong(categoryId));
					}
					param.put("categoryIdList", categoryIdList);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					if (null != categoryList && categoryList.size() > 0) {
						String value = "";
						for (ProductCategoryEntity productCategory : categoryList) {
							value += productCategory.getCategoryName() + "、";
						}
						value = value.substring(0, value.length() - 1);
						filterNameList.add(new ProductSearchFilterEntity("v_categoryId", "类型", value));
					}
					model.addAttribute("categoryList", categoryList);
				} else {
					param.put("parentCategoryId", productCategoryId);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					categoryIdList.add(Long.parseLong(productCategoryId));
					ProductCategoryEntity pce = productCategoryService.getProductCategoryById(Long.parseLong(productCategoryId));
					filterNameList.add(new ProductSearchFilterEntity("v_categoryId", "类型", pce.getCategoryName()));
					// 如果没有子分类，那就还是显示它自己吧
					if(null == categoryList || categoryList.size() == 0) {
						categoryList.add(pce);
					}
					model.addAttribute("categoryList", categoryList);
				}
//				param.put("parentCategoryId", productCategoryId);
//				List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
//				categoryIdList.add(Long.parseLong(productCategoryId));
//				ProductCategoryEntity pce = productCategoryService.getProductCategoryById(Long.parseLong(productCategoryId));
//				filterNameList.add(new ProductSearchFilterEntity("v_categoryId", "类型", pce.getCategoryName()));
//				model.addAttribute("categoryList", categoryList);
			}
			/* 第二种 */
			param.put("searchKey", productSearchKey);
			/**
			 * 4、组装参数并执行商品查询
			 * */
			// 筛选项查询条件
			if (StringUtil.isNotEmpty(propertyFilter)) {
				List<ProductPropertyEntity> propertyList = JSONArray.parseArray(propertyFilter, ProductPropertyEntity.class);
				// 添加页面筛选条件
				for (ProductPropertyEntity property : propertyList) {
					filterNameList.add(new ProductSearchFilterEntity("v_propertyFilter", property.getPropertyName(), property.getPropertyValue()));
				}
				param.put("propertyList", propertyList);
			} else {
				param.put("propertyList", Collections.EMPTY_LIST);
			}
			// 品牌
			param.put("brandId", brandId);
			if (StringUtil.isNotEmpty(brandIds)) {
				param.put("brandIds", "(" + brandIds + ")");
			}
			// 价格(最低价-最高价)
			param.put("minPrice", minPrice);
			param.put("maxPrice", maxPrice);
			model.addAttribute("filterNameList", filterNameList);
			// 商品类型ids 查询参数
			StringBuffer categoryIds = new StringBuffer("(");
			if (null != categoryIdList && categoryIdList.size() > 0) {
				for (Long categoryId : categoryIdList) {
					categoryIds.append(categoryId).append(",");
				}
				categoryIds = new StringBuffer(categoryIds.substring(0, categoryIds.length() - 1)).append(")");
				param.put("categoryIds", StringUtil.isNotEmpty(categoryIds) ? categoryIds.toString() : null);
			}
			// 排序
//			param.put("sortField", sortField);
//			param.put("sortType", sortType);
			
			// 【关键字查询】查询商品列表（模糊匹配商品名称 or 类型名称 or 品牌名称）
			// 【筛选项】品牌查询|类型查询|筛选项查询
			PageParam pageParam = super.getPageParam(request, 50);
			param.put("customerLevel", getCustomerLevel());
			param.put("isLogin", isLogin(request) ? "1" : "0");
			param.put("customerId", getCustomerId());
			param.put("searchKey", productSearchKey);
			param.put("productTag", productTag);
			/**
			 *  加上报价单查询标识 
			 * */
			param.put("isQuatoSearch", "1");
			PageBean pageBean = productService.listProductPageForIndex(pageParam, param);
			model.addAttribute("productList", pageBean.getRecordList());
			model.addAttribute("pageBean", pageBean);
			/**
			 * 5、查询完成，获取页面条件品牌
			 * */
			/* 查询商品属性、查询品牌，就可以用父级分类去查询 */
			// T1、开始获取品牌列表
			List<ProductBrandEntity> brandList = null;
			// 搜索相关品牌
			brandList = productBrandService.listAllBrandForIndex(param);
			// 分类如果没关联，那就再去附近看下
			if(null == brandList || brandList.size() == 0) {
				// 如果没获取到，那就取其父级分类
				param.put("categoryIdList", categoryIdList);
				List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
				// 商品类型ids 查询参数
				StringBuffer categoryIdString = new StringBuffer("(");
				for (ProductCategoryEntity productCategory : categoryList) {
					if (null != categoryList && categoryList.size() > 0) {
						categoryIdString.append(productCategory.getParentCategoryId()).append(",").append(productCategory.getId()).append(",");
					}
				}
				categoryIdString = new StringBuffer(categoryIdString.substring(0, categoryIdString.length() - 1)).append(")");
				param.put("categoryIds", StringUtil.isNotEmpty(categoryIdString) ? categoryIdString.toString() : null);
				brandList = productBrandService.listAllBrandForIndex(param);
				// 还原子分类
				param.put("categoryIds", StringUtil.isNotEmpty(categoryIds) ? categoryIds.toString() : null);
			}
			model.addAttribute("brandList", brandList);
			// T2、品牌处理
			// key-value = brand_id-brand_name 方面页面显示品牌名称
			Map<Long, String> brandNameMap = new HashMap<Long, String>();
			// 处理品牌的分类，根据首字符中进行A~Z分类存在到List,到页面中循环展示
			Map<String, List<ProductBrandEntity>> brandMap = new HashMap<String, List<ProductBrandEntity>>();
			if (brandList != null && brandList.size() > 0) {
				for (ProductBrandEntity brand : brandList) {
					brandNameMap.put(brand.getId(), brand.getBrandNameCh());
					if (StringUtil.isNotNull(brand.getBrandLetterFrist())) {
						String key = brand.getBrandLetterFrist().substring(0, 1).toUpperCase();
						if (brandMap.containsKey(key)) {
							List<ProductBrandEntity> tmpBrandList = brandMap.get(key);
							tmpBrandList.add(brand);
						} else {
							List<ProductBrandEntity> tmpBrandList = new ArrayList<ProductBrandEntity>();
							tmpBrandList.add(brand);
							brandMap.put(key, tmpBrandList);
						}
					}
				}
			}
			List<List<ProductBrandEntity>> showBrandList = new ArrayList<List<ProductBrandEntity>>();
			for (char c = 'A'; c <= 'Z'; c++) {
				if (brandMap.containsKey(String.valueOf(c))) {
					showBrandList.add(brandMap.get(String.valueOf(c)));
				} else {
					showBrandList.add(Collections.EMPTY_LIST);
				}
			}
			model.addAttribute("showBrandList", showBrandList);
			// 排序规则（综合（指定）、人气（浏览次数）、新品（审核时间？？）、价格（基价））
			// 添加筛选条件
			if (StringUtil.isNotEmpty(brandId) && brandNameMap.containsKey(Long.parseLong(brandId))) {
				filterNameList.add(new ProductSearchFilterEntity("v_brandId", "品牌", brandNameMap.get(Long.parseLong(brandId))));
			}
			if (StringUtil.isNotEmpty(brandIds)) {
				// 添加筛选条件
				StringBuffer brandBuf = new StringBuffer();
				for (String brandIdStr : brandIds.split(",")) {
					brandBuf.append(brandNameMap.get(Long.parseLong(brandIdStr)));
				}
				if (StringUtil.isNotEmpty(brandBuf)) {
					filterNameList.add(new ProductSearchFilterEntity("v_brandIds", "品牌", brandBuf.substring(0, brandBuf.length() - 1)));
				}
			}
			
			/**
			 * 6、商品属性筛选项
			 * */
			boolean isAll = false;
			if (StringUtil.isEmpty(productCategoryId) && StringUtil.isEmpty(productSearchKey)) {
				// 无商品分类参数、无商品关键字参数，则查询所有商品
				// 商品分类则显示
				isAll = true;
				// 查询所有一级分类
				param.put("parentCategoryId", 0);
				List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
				model.addAttribute("categoryList", categoryList);
			} else if (StringUtil.isNotNull(productSearchKey) && StringUtil.isEmpty(productCategoryId)) {
				// 有关键字参数，没有商品分类参数
				// 那么商品分类则汇总所有已查询到的商品
				param.put("productName", productSearchKey);
				param.put("normalPro", "1");// 正常商品，过滤掉已下架商品
				param.put("brandCode", brandId);
				List<ProductEntity> proList = productService.listProduct(param);
				for (ProductEntity product : proList) {
					categoryIdList.add(product.getProductCategoryId());
				}
				param.put("categoryIdList", categoryIdList);
				if (categoryIdList.size() > 0) {
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					List<ProductCategoryEntity> opCategoryList = new ArrayList<ProductCategoryEntity>();
					for (ProductCategoryEntity productCategory : categoryList) {
						// 如果是一级分类，则去掉，理论上只保留二级分类
						int length = productCategory.getPath().length() - productCategory.getPath().replaceAll("\\|", "").length();
						if (length == 2) {
							opCategoryList.add(productCategory);
						}
					}
					model.addAttribute("categoryList", opCategoryList);
				}
			}
			if (!isAll) {
				// 根据商品分类去获取属性筛选项
				List<ProductCategoryPropertyFilterEntity> filterList = productCategoryPropertyFilterService.listProductCategoryPropertyFilterForIndex(param);
				if((null == filterList || filterList.size() == 0) && categoryIdList.size() > 0) {
					// 如果没获取到，那就取其父级分类
					param.remove("parentCategoryId");
					param.put("categoryIdList", categoryIdList);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					// 商品类型ids 查询参数
					if(null != categoryList && categoryList.size() > 0) {
						StringBuffer categoryIdString = new StringBuffer("(");
						for (ProductCategoryEntity productCategory : categoryList) {
							categoryIdString.append(productCategory.getParentCategoryId()).append(",").append(productCategory.getId()).append(",");
						}
						categoryIdString = new StringBuffer(categoryIdString.substring(0, categoryIdString.length() - 1)).append(")");
						param.put("categoryIds", StringUtil.isNotEmpty(categoryIdString) ? categoryIdString.toString() : null);
						filterList = productCategoryPropertyFilterService.listProductCategoryPropertyFilterForIndex(param);
						// 还原子分类
						param.put("categoryIds", StringUtil.isNotEmpty(categoryIds) ? categoryIds.toString() : null);
					}
				}
				if (filterList != null && filterList.size() > 0) {
					for (ProductCategoryPropertyFilterEntity filter : filterList) {
						if (StringUtil.isNotEmpty(filter.getPropertyValue())) {
							String[] pvs = filter.getPropertyValue().split(",");
							List<String> tmpList = new ArrayList<>();
							for (String pv : pvs) {
								tmpList.add(pv);
							}
							filter.setPropertyValueList(tmpList);
						}
					}
				}
				model.addAttribute("filterList", filterList);
			}
			// 价格
			if (StringUtil.isNotEmpty(minPrice)) {
				if ("999999999".equals(minPrice)) {
					filterNameList.add(new ProductSearchFilterEntity("v_price", "价格", minPrice + "元以上"));
				} else {
					filterNameList.add(new ProductSearchFilterEntity("v_price", "价格", minPrice + "~" + maxPrice));
				}
			} else {
				if (StringUtil.isNotEmpty(minPrice) && !"999999999".equals(minPrice)) {
					filterNameList.add(new ProductSearchFilterEntity("v_price", "价格", maxPrice + "元以下"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		/** 1.为页面赋予初始化数据 */
		model.addAttribute("searchKey", productSearchKey);
		model.addAttribute("categoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("brandIds", brandIds);
		model.addAttribute("minPrice", minPrice);
		model.addAttribute("maxPrice", maxPrice);
		model.addAttribute("propertyFilter", StringUtil.isNotEmpty(propertyFilter) ? propertyFilter.replace("\"", "'") : "");
		model.addAttribute("productTag", productTag);
		request.setAttribute("page", "quotation");

		return "pc/my/quotation/my_quotation";
	}
	
	/**
	 * 初始化所有商品分类，建立从属关系
	 * @return List<ProductCategoryEntity>    
	 * @author xu_cc  
	 * @throws Exception exception
	 * @Date 创建时间：2018年1月29日 上午11:49:26
	 */
	private List<ProductCategoryEntity> initProductCategoryData() {
		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		// 所有商品类型
		List<ProductCategoryEntity> topCategoryList = productCategoryService.listProductCategoryForIndex(param);
		if (topCategoryList != null && topCategoryList.size() > 0) {
			for (ProductCategoryEntity category : topCategoryList) {
				if (StringUtil.isNotEmpty(category.getSubCategoryListStr())) {
					List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("[" + category.getSubCategoryListStr() + "]",
					        ProductCategoryEntity.class);
					category.setSubCategoryList(tmpCategoryList);
				}
			}
		}
		return topCategoryList;
	}
	
	/**
	 * 获取报价单列表数据（导出、打印）
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2018年1月27日 下午1:23:19
	 */
	private List<ProductEntity> getQuotationListOfExportAndPrint(HttpServletRequest request) {
		PageParam pageParam = super.getPageParam(request);
		pageParam.setNumPerPage(1000000);
		
		Map<String, Object> param= new HashMap<String, Object>();
		
		param.put("customerLevel", getCustomerLevel());
		param.put("isLogin", isLogin(request)?"1":"0");
		String propertyFilter = request.getParameter("propertyFilter");
		if(StringUtil.isNotEmpty(propertyFilter)){
			List<ProductPropertyEntity> propertyList = JSONArray.parseArray(propertyFilter, ProductPropertyEntity.class);
			param.put("propertyList", propertyList);
		}else{
			param.put("propertyList", Collections.EMPTY_LIST);
		}
		
		String categoryId = request.getParameter("categoryId");
		param.put("categoryId", StringUtil.isEmpty(categoryId) ? null : categoryId);
		String brandId = request.getParameter("brandId");
		param.put("brandId", StringUtil.isEmpty(brandId) ? null : brandId);
		String categoryIds = request.getParameter("categoryIds");
		param.put("categoryIds", StringUtil.isEmpty(categoryIds) ? null : categoryIds);
		String parentCategoryId = request.getParameter("parentCategoryId");
		param.put("parentCategoryId", StringUtil.isEmpty(parentCategoryId) ? null : parentCategoryId);
		String categoryPath = request.getParameter("categoryPath");
		param.put("categoryPath", StringUtil.isEmpty(categoryPath) ? null : categoryPath);
		String sortField = request.getParameter("sortField");
		param.put("sortField", StringUtil.isEmpty(sortField) ? null : sortField);
		String sortType = request.getParameter("sortType");
		param.put("sortType", StringUtil.isEmpty(sortType) ? null : sortType);
		String minPrice = request.getParameter("minPrice");
		param.put("minPrice", StringUtil.isEmpty(minPrice) ? null : minPrice);
		String maxPrice = request.getParameter("maxPrice");
		param.put("maxPrice", StringUtil.isEmpty(maxPrice) ? null : maxPrice);
	
		PageBean pageBean = productService.listProductPageForIndex(pageParam, param);
		List<ProductEntity> quotationList = (List) pageBean.getRecordList();
		return quotationList;
	}
	
	/**
	 * 导出报价单
	 * @param request
	 */
	@RequestMapping("/exportQuotation")
	public void exportQuotation(HttpServletRequest request, HttpServletResponse response){
		
		try {
			List<ProductEntity> quotationList = getQuotationListOfExportAndPrint(request);
			List<String> headNames = new ArrayList<String>();
			//headNames.add("序号");
			headNames.add("编码");
			headNames.add("商品名称");
			headNames.add("价格");
			
			List<String> fieldNames = new ArrayList<String>();
			fieldNames.add("productCode");
			fieldNames.add("productName");
			fieldNames.add("basePrice");
			
			expToExcel07(request, response, headNames, fieldNames, "QuotationInfo.xlsx", quotationList);
		} catch (Exception e) {
			handleException("导出报价单信息失败", logger, e);
		}
	}
	
	/**
	 * 跳转到报价单打印页
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2018年1月27日 下午1:28:41
	 */
	@RequestMapping("/toPrintQuotation")
	public String toPrintQuotation( HttpServletRequest request) {
		
		try {
			List<ProductEntity> quotationList = getQuotationListOfExportAndPrint(request);
			request.setAttribute("productList", quotationList);
		} catch (Exception e) {
			handleException("打印报价单信息失败", logger, e);
		}
		return "pc/my/quotation/my_quotation_print";
	}
}
